package org.springframework.security.oauth2.provider.client;

import com.yhy.common.security.exception.MyAuth2Exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.NoSuchClientException;

/**
 * @author Dave Syer
 */
@Slf4j
public class ClientDetailsUserDetailsService implements UserDetailsService {

    private final ClientDetailsService clientDetailsService;
    private String emptyPassword = "";

    public ClientDetailsUserDetailsService(ClientDetailsService clientDetailsService) {
        this.clientDetailsService = clientDetailsService;
    }

    /**
     * @param passwordEncoder the password encoder to set
     */
    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.emptyPassword = passwordEncoder.encode("");
    }

    /**
     * 重写源码解决oauth2 获取token header中basic认证失败
     *
     * @param username username
     * @return UserDetails
     * @throws UsernameNotFoundException ex
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ClientDetails clientDetails;
        try {
            clientDetails = clientDetailsService.loadClientByClientId(username);
        } catch (NoSuchClientException e) {
            log.error("认证异常::: {}", e.getMessage());
            throw new MyAuth2Exception(e.getMessage(), e);
        }
        String clientSecret = clientDetails.getClientSecret();
        if (clientSecret == null || clientSecret.trim().length() == 0) {
            clientSecret = emptyPassword;
        }
        return new User(username, clientSecret, clientDetails.getAuthorities());
    }

}
